package com.woyao;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.OrientationHelper;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.woyao.core.model.GetChildHowResponse;
import com.woyao.core.model.How;
import com.woyao.core.service.HowService;
import com.woyao.core.util.ServiceFactory;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import retrofit2.Call;

public class FilterHow extends AppCompatActivity {
    TextView howtitle = null;
    HashMap<String,String> parents = new HashMap<String,String>() ;

    private  String curhow = "";

    LinearLayoutManager allLayoutManager = null;
    private RecyclerView alllist = null;
    private TreeAdapter allAdapter;

    Boolean changed = false;
    ProgressDialog progressDialog;

    private  String from = "";
    Integer HOW_CODE  =666;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_filter_how);

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);

        setSupportActionBar(toolbar);
        final ActionBar ab = getSupportActionBar();
        //       ab.setHomeAsUpIndicator(R.drawable.icon_menu); // set a custom icon for the default home button
        ab.setDisplayShowHomeEnabled(true); // show or hide the default home button
        ab.setDisplayHomeAsUpEnabled(true);
        ab.setDisplayShowCustomEnabled(true); // enable overriding the default toolbar layout
//        ab.setDisplayShowTitleEnabled(false); // disable the default title element


        alllist = (RecyclerView) findViewById(R.id.id_how_list);
        allLayoutManager = new LinearLayoutManager(this);
        allLayoutManager.setOrientation(OrientationHelper.VERTICAL);
        alllist.setLayoutManager(allLayoutManager);
        alllist.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL_LIST));

        TextView roottitle = (TextView) findViewById(R.id.how_roottitle);

        roottitle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                curhow ="";
                howtitle.setText(  curhow );
                loadAllData();
            }
        });

        howtitle = (TextView) findViewById(R.id.alltitle);

        Button gobackbtn = (Button) findViewById(R.id.goback);

        gobackbtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (parents.get(curhow ) != null) {

                    curhow = parents.get(curhow ) ;
                    howtitle.setText(  curhow );
                    loadAllData();
                }
            }
        });

        Intent intent = getIntent();
        from = intent.getStringExtra("from");

        if  (from.equals("register")) {
            this.setTitle("2/4. 选择合作方式 ");
        }else{
            this.setTitle("选择合作方式");
        }


        loadAllData();

    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        Intent intent = new Intent();
        intent.putExtra("changed", changed );
        setResult(0, intent);
        finish();

        return true;
    }




    private void loadAllData(){
        progressDialog = new ProgressDialog(this);
        progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        progressDialog.setMessage("拼命加载中······");
        progressDialog.show();

        AsyncTask<Void,Void,GetChildHowResponse> task =
                new AsyncTask<Void, Void, GetChildHowResponse>() {
                    @Override
                    protected GetChildHowResponse doInBackground(Void... params) {
                        HowService svc = ServiceFactory.get(HowService.class);
                        Call<GetChildHowResponse> responseCall = svc.getChildHow(curhow,WoyaoooApplication.userId);
                        try {
                            GetChildHowResponse response = responseCall.execute().body();
                            return response;
                        } catch (IOException e) {
                            e.printStackTrace();
                            return null;
                        }
                    }
                    @Override
                    protected void onPostExecute(final GetChildHowResponse response) {
                        progressDialog.dismiss();
                        ArrayList<How> hows = response.getHowList();
                        renderAll(hows);
                    }
                    @Override
                    protected void onCancelled() {
                        progressDialog.dismiss();
                    }
                };
        task.execute();
    }


    private void renderAll( ArrayList<How> thehow ){


        ArrayList<Map<String,String>> mapList = new ArrayList<>();

        for(How howww : thehow){
            HashMap<String,String> map = new HashMap<>();
            map.put("no", howww.getNo());
            map.put("name", howww.getName());
            map.put("description", howww.getDescription());
            map.put("childs", howww.getChilds() +"");
            mapList.add(map);
        }
        allAdapter = new TreeAdapter(this,  mapList );

        allAdapter.setChangedHandler(new TreeAdapter.Changed() {
            @Override
            public void itemSelected(Map<String, String> one) {
                if (from.equals("mydemand") || from.equals("register"))
                {
                    Intent intent = new Intent();
                    intent.putExtra("from", from);
                    intent.putExtra("no", one.get("no"));
                    intent.putExtra("name", one.get("name"));
                    intent.setClass(FilterHow.this, DemandActivity.class);
                    startActivityForResult(  intent , HOW_CODE);

                }else {
                    Intent intent = new Intent();
                    intent.putExtra("no", one.get("no"));
                    intent.putExtra("name", one.get("name"));
                    setResult(666, intent);
                    finish();
                }
            }




            @Override
            public void itemGetChildren(Map<String, String> one) {

                parents.put(one.get("name"), curhow );
                curhow = one.get("name");
                howtitle.setText( curhow );
                loadAllData();
            }
        });


        this.alllist.setAdapter(allAdapter);

    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == HOW_CODE){
            if (from.equals("mydemand")) {
                Intent intent = new Intent();
                intent.putExtra("changed", true);
                setResult(666, intent);
                finish();
            }
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK) {
            Intent intent = new Intent();
            intent.putExtra("changed", changed );
            setResult(0, intent);
            finish();
            return false;
        }
        return super.onKeyDown(keyCode, event);
    }

}

